package com.hcj.springcloud.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcj.springcloud.data.MockData;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

import static org.apache.poi.ss.usermodel.Workbook.PICTURE_TYPE_PNG;

@RestController
@RequestMapping("/excel")
public class ExcelDemoController {

    /**
     * 生成excel && 插入picture到excel中
     */
    @RequestMapping("/genExcel")
    public void genExcel(@RequestBody(required = false) JSONObject dto, HttpServletResponse response) throws IOException {
        // 1. 准备好数据
        String imgBase64 = "";
        JSONArray data = new JSONArray();
        if (dto != null) {
            imgBase64 = dto.getString("imgBase64");
            data = dto.getJSONArray("data");
        }
        if (imgBase64 == null || "".equals(imgBase64)) {
            imgBase64 = MockData.PIE_IMG_BASE64;
        }
        if (data == null || data.isEmpty()) {
            data = JSON.parseArray(MockData.PIE_IMG_DATA);
        }
        // 2. 写入excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        Workbook wb = writer.getWorkbook();
        // 2.1 写入data
        writer.addHeaderAlias("name", "name");
        writer.addHeaderAlias("value", "value");
        writer.write(data);
        // 2.2 写入img
        Sheet sheet = writer.getSheet();
        Drawing<?> patriarch = sheet.createDrawingPatriarch();
        // 2.2.1 指定图片写入的位置
        XSSFClientAnchor hssfClientAnchor = new XSSFClientAnchor(5, 5, 5, 5, (short) 0, 10 + 1, (short) 5, 10 + 26);
        // 2.2.2 添加图片资源
        byte[] imgBase64ToByte = imgBase64ToByte(imgBase64);
        int picIndex = wb.addPicture(imgBase64ToByte, PICTURE_TYPE_PNG);
        patriarch.createPicture(hssfClientAnchor, picIndex);
        // 3. 导出excel
        String fileName = "饼图_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
        response.setHeader("content-type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream);
        outputStream.flush();
        outputStream.close();

    }

    private byte[] imgBase64ToByte(String imgBase64) {
        String[] imgBase64Arr = imgBase64.split(",");
        String imgBase64Encoded = imgBase64Arr[1];
        byte[] decode = Base64.getDecoder().decode(imgBase64Encoded);
        return decode;
    }
}
